/* 登录 & 注册 */
const express = require('express')
const router = express.Router()
const User = require('../../model/user')
const keys = require('../../config/keys')
const md5 = require('md5')
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const passport = require('passport')

//$route Get api/user/test
//desc  返回请求的json数据
//access public
router.get('/test', (req, res) => {
    console.log('有人访问了接口');
    res.json({ msg: '用户信息接口' })
})

//$route Post api/user/register
//desc  返回请求的json数据
//access public
router.post('/register', (req, res) => {
    //    console.log(req.body)
    //查询数据库中是否拥有邮箱
    User.findOne({ email: req.body.email })
        .then((user) => {
            if (user) {
                return res.status(400).json('邮箱已被注册' )
            } else {
                const avatar = gravatar.url(req.body.email, { s: '200', r: 'pg', d: '404' });
                const newUser = new User({
                    name: req.body.name,
                    email: req.body.email,
                    avatar,
                    password: req.body.password,
                    identity: req.body.identity
                })
                newUser.password = md5(newUser.password)
                newUser.save()
                    .then(user => res.json(user))
                    .catch(err => console.log(err))
            }
        })
})

//$route Post api/user/login
//desc  返回token jwt passport
//access public

router.post('/login', (req, res) => {
    const email = req.body.email
    const password = req.body.password
    //查询数据库
    User.findOne({ email })
        .then(user => {
            if (!user) {
                return res.status(404).json( "用户不存在" )
            }
            if (md5(password) === user.password) {
                const rule = { 
                    id: user.id, 
                    name: user.name,
                    avatar:user.avatar,
                    identity:user.identity    
                }
                //jwt.sign('规则','加密名字','过期时间','箭头函数')
                jwt.sign(rule, keys.secretOrKey, { expiresIn: 3600 }, (err, token) => {
                    res.json({
                        success: true,
                        token: "Bearer " + token
                    })
                })
            } else {
                res.status(400).json( '密码错误' )
            }

        })
})

//$route Get api/user/current
//desc  返回current user
//access private

router.get('/current', passport.authenticate('jwt', { session: false }), (req, res) => {
    res.json({
        id: req.user.id,
        name: req.user.name,
        email: req.user.email,
        identity:req.user.identity
    })
})
module.exports = router